var express = require('express');
var logger = require('./logger');
var con = require('./controller');
var qiniu = require('qiniu');

function auth(req, res, next) {
    if(!req.session.user) {
        res.redirect('/login');
    } else {
        next()
    }
}

function authAdmin(req, res, next) {
    if(req.session.user) {
        if(req.session.user.role === 'user') {
            res.redirect('/');
        } else {
            next();
        }
    } else {
        res.redirect('/login');
    }
}
module.exports = function(app, logger) {
    // app.get('/', auth, function(req, res) {
    //     res.render('index', {title: 'hellow express'})
    // });

    app.get('/', auth, con.Site.index);

    app.get('/article/write', auth, function(req, res) {
        res.render('article/write', {title: 'hellow express'})
    });

    app.get('/article/manage', auth, function(req, res) {
        res.render('article/manage', {title: 'hellow express'})
    });



    app.get('/login', function(req, res) {
        res.render('login', {title: 'hellow express'})
    });

    app.get('/chatRoom', auth, function(req, res) {
        res.render('chatRoom/index', {title: '聊天室'});
    });

    // admin
    app.get('/admin', authAdmin, function(req, res) {
        console.log('req.session', req.session.user);
        res.render('admin/admin', {title: 'admin'});
    });

    // // 用户管理
    app.get('/admin/user', authAdmin, function(req, res) {
        res.render('admin/user', {title: '用户管理'});
    });

    // api
    app.get('/api/qiniu/getToken', function(req, res) {
        var accessKey = 'k6KUdarbJ6QDrv6_o6hHIVb2IA-OXhDMrgAi6jBn';
        var secretKey = 'gbN4U0d5-rdec7mGK-y0IkZZLgYajh6cejvuO-tP';
        var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
        var options = {
            scope: 'zjl606-web', // bucket
            expires: 7200
        };
        var putPolicy = new qiniu.rs.PutPolicy(options);
        var uploadToken=putPolicy.uploadToken(mac);
        res.json({
            token: uploadToken,
        });
    });
    app.post('/api/logout', function(req, res) {
        
        logger.info('用户：' + req.session.user.userName + '(' + req.session.user.role + ')成功退出！');
        req.session.user = null;
        res.json({
            status: 'success!',
            message: '退出成功！'
        });

    });
    app.post('/api/admin/login', con.User.login);
    app.post('/api/article/add', con.Article.add);
    app.get('/api/article/getArticleByUserId', con.Article.getArticleByUserId);
    app.post('/api/article/delete', con.Article.delete);
    app.get('/api/user/getUser', con.User.getUser);
    app.post('/api/user/addUser', con.User.addUser);
    app.post('/api/user/delete', con.User.delete);
    app.post('/api/user/addFriend', con.User.addFriend);
    app.get('/api/user/getUnFriend', con.User.getUnFriend);
    app.get('/api/user/getFriendList', con.User.getFriendList);

}